package com.itheima.redbaby.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.itheima.redbaby.BaseActivity;
import com.itheima.redbaby.GloableParams;
import com.itheima.redbaby.R;
import com.itheima.redbaby.bean.CartItem;
import com.itheima.redbaby.bean.CartProduct;
import com.itheima.redbaby.bean.Product;
import com.itheima.redbaby.bean.ProductProperty;
import com.itheima.redbaby.engine.BaseEngine;
import com.itheima.redbaby.engine.impl.CheckOutEngineImpl;
import com.itheima.redbaby.net.HttpUtil;
import com.itheima.redbaby.utils.ImageUtil;
import com.itheima.redbaby.utils.ListViewUtils;
import com.itheima.redbaby.utils.PromptManager;

//结算中心页面
public class SummaryPaymentActivity extends BaseActivity implements OnClickListener {//继承
	private static final int PAYWAYREQUEST =100;//支付方式状态码
	private static final int SENDTIMEREQUEST =101;//支付方式状态码
	private static final int YOUHUIKAREQUEST = 102;
	private static final int FAPIAOREQUEST =103;
	private  static final int ORDERREQUEST = 104;
	private static final int PERSONINFO =105;

	private TextView head_shopping_cart;
	private TextView head_submit_order;
	private RelativeLayout summary_receiver_rel;
	private RelativeLayout summary_favorable_rel;
	private RelativeLayout request_invoice;
	private TextView ordr_submit_bottom_text;
	private RelativeLayout summary_sendTime_rel;
	private RelativeLayout summary_sendeway_rel;
	private RelativeLayout summary_payType_rel;

	private TextView summary_payway_detail;
	private TextView summary_sendway_detail;
	private TextView summary_sendtime_detail;
	private TextView summary_useyouhuijuan_detail;
	private ListView summary_product_list;
	private TextView summary_total_buycount_text;
	private TextView summary_total_bonus_text;
	private TextView summary_total_money_text;
	private TextView summary_freight_money_text;
	private TextView summary_cuxiao_money_text;
	private TextView summary_shouldpay_money_text;
	
	private int summary_total_buycount;//总共买的数量
	private float summary_total_bonus;//商品 总金额 原始金额
	private float summary_freight_money=10;//运费 默认是10
	private int summary_cuxiao_money=30;//促销金额
	private float summary_shouldpay_money;//应付金额
	
	//使用优惠卡：type1 优惠卡信息一 type 2：。。二  3.。。
	private int payType=3;//支付方式
	private int sendWayType=1;//送货方式类型
	private int sendTimeType=3;//送货时间类型
	//1 => 周一至周五送货 2=> 双休日及公众假期送货 3=> 时间不限，工作日双休日及公众假期均可送货
	private int youHuiKaType=1;//优惠劵信息
	
	private int ranOrderId=1;//订单id
	
	private float productScore=0;//商品积分
	
	private int invoice_info_id;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("结算中心界面");
		//请求服务器数据 用户最先看到的是服务端过来的数据 
		CheckOutEngineImpl checkOutEngineImpl=new CheckOutEngineImpl();
		Map<String, Object> map=new HashMap<String, Object>();
		List<Product> productlist=new ArrayList<Product>();
		Product product=new Product();
		product.setId(120000);
		product.setNumber(3);
		productlist.add(product);
		Product product1=new Product();
		product1.setId(120000);
		product1.setNumber(3);
		productlist.add(product1);
		map.put("productlist", productlist);
//		JSONObject json = checkOutEngineImpl.getJson(BaseEngine.TYPE_POST, GloableParams.LZLURLCOMMON+GloableParams.LZLCONTENT, map);
		init();//初始化界面
	}
	
	private void init() {//
		 //获取购物车数据 
		if(GloableParams.cartitemlist.size()==0){
				Toast.makeText(this, "购物车为空,请添加商品", 0).show();
				finish();
				return;
		}
		System.out.println(GloableParams.cartMap.toString());
		setContentView(R.layout.summary_payment_center_activity);//加载页面
		
		head_shopping_cart = (TextView) findViewById(R.id.head_shopping_cart);
		head_shopping_cart.setOnClickListener(this);
		
		head_submit_order = (TextView) findViewById(R.id.head_submit_order);
		head_submit_order.setOnClickListener(this);
		
		summary_receiver_rel = (RelativeLayout) findViewById(R.id.summary_receiver_rel);
		summary_receiver_rel.setOnClickListener(this);
		
		summary_payType_rel = (RelativeLayout) findViewById(R.id.summary_payType_rel);
		summary_payType_rel.setOnClickListener(this);
		
		summary_sendTime_rel = (RelativeLayout) findViewById(R.id.summary_sendTime_rel);
		summary_sendTime_rel.setOnClickListener(this);
		
		summary_sendeway_rel = (RelativeLayout) findViewById(R.id.summary_sendeway_rel);
		summary_sendeway_rel.setOnClickListener(this);
		
		summary_favorable_rel = (RelativeLayout) findViewById(R.id.summary_favorable_rel);
		summary_favorable_rel.setOnClickListener(this);
		
		request_invoice = (RelativeLayout) findViewById(R.id.request_invoice);
		request_invoice.setOnClickListener(this);
		
		ordr_submit_bottom_text = (TextView) findViewById(R.id.ordr_submit_bottom_text);
		ordr_submit_bottom_text.setOnClickListener(this);
		
		summary_payway_detail = (TextView) findViewById(R.id.summary_payway_detail);
		summary_sendtime_detail = (TextView) findViewById(R.id.summary_sendtime_detail);
		
		summary_sendway_detail = (TextView) findViewById(R.id.summary_sendway_detail);
		summary_useyouhuijuan_detail = (TextView) findViewById(R.id.summary_useyouhuijuan_detail);
		summary_getinvoice_detail = (TextView) findViewById(R.id.summary_getinvoice_detail);
		
		summary_receiver_info_text = (TextView) findViewById(R.id.summary_receiver_info_text);
		
		//全局的变量 购物车中集合
		
		summary_product_list = (ListView) FId(R.id.summary_product_list);
		adapter = new MyBaseAdapter();
		productIds="";//将他设置为空
		summary_product_list.setAdapter(adapter);
//		new ListViewUtils().setListViewHeightBasedOnChildren(summary_product_list);
		
		summary_total_buycount_text = (TextView) FId(R.id.summary_total_buycount_text);//总计买了多少件
		summary_total_bonus_text = (TextView) FId(R.id.summary_total_bonus_text);//总商品价格
		summary_freight_money_text = (TextView) FId(R.id.summary_freight_money_text);//运费
		summary_cuxiao_money_text = (TextView) FId(R.id.summary_cuxiao_money_text);//促销金额
		summary_shouldpay_money_text = (TextView) FId(R.id.summary_shouldpay_money_text);//应付金额
		fillData();
	}
	//填充数据 在子线程中
	private void fillData() {
		for (int i = 0; i < GloableParams.cartitemlist.size(); i++) {
			CartItem cartItem = GloableParams.cartitemlist.get(i);
			int productprom = cartItem.getProductprom();
			summary_total_buycount+=productprom;
			CartProduct product = cartItem.getProduct();
			product.getPrice();
//			summary_total_bonus+=product.getPrice();
			String totalPrice = GloableParams.cartMap.get("totalPrice").toString();
//			summary_item_num_text.setText("小计");
			summary_total_bonus+=product.getPrice()*productprom;
		}
		summary_shouldpay_money=summary_total_bonus-summary_cuxiao_money+summary_freight_money;
		summary_total_buycount_text.setText(""+summary_total_buycount);
		summary_total_bonus_text.setText(""+summary_total_bonus);
		summary_freight_money_text.setText(""+summary_freight_money);
		summary_cuxiao_money_text.setText(""+summary_cuxiao_money);	
		summary_shouldpay_money_text.setText(summary_shouldpay_money+"");
//		new Thread(){
//			public void run() {
////				private float summary_total_bonus;//商品 总金额 原始金额
////				private float summary_freight_money=10;//运费 默认是10
////				private float summary_cuxiao_money=30;//促销金额
//			};
//		}.start();
	}
	
	class MyBaseAdapter extends BaseAdapter{
		@Override
		public int getCount() {
			return GloableParams.cartitemlist.size();
		}
		@Override
		public Object getItem(int position) {
			return GloableParams.cartitemlist.get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = View.inflate(SummaryPaymentActivity.this, R.layout.summary_car_listitem, null);
			//商品名称
			TextView shopcar_item_prodName_text = (TextView) v.findViewById(R.id.shopcar_item_prodName_text);
			TextView shopcar_item_prodId_text = (TextView) v.findViewById(R.id.shopcar_item_prodId_text);
			TextView shopcar_item_prodPrice_text = (TextView) v.findViewById(R.id.shopcar_item_prodPrice_text);
			TextView shopcar_item_num_text = (TextView) v.findViewById(R.id.shopcar_item_num_text);
			TextView shopcar_item_subtotal_text = (TextView) v.findViewById(R.id.shopcar_item_subtotal_text);
			TextView summary_item_num_text = (TextView) v.findViewById(R.id.summary_item_num_text);
			ImageView shopcar_item_prodImage_img = (ImageView) v.findViewById(R.id.shopcar_item_prodImage_img);
			
			CartItem cartItem = GloableParams.cartitemlist.get(position);
			CartProduct product = cartItem.getProduct();
			int productId= product.getProduct_id();
			productIds+=productId+",";
			float score = product.getScore();//商品积分 
			productScore+=score;
			float productPrice = product.getPrice();//商品单价
			String imgUrl = product.getPicpath();//图片路径
			//加载图片
			ImageUtil.loadImageFromUrl(shopcar_item_prodImage_img, imgUrl);
			
			String productName = product.getName();//商品名称
			shopcar_item_prodName_text.setText(productName);
//			shopcar_item_prodName_text.setText("商品名称");
			List<ProductProperty> productPropertyList = product.getProductPropertyList();
			for (ProductProperty productProperty : productPropertyList) {
				if(productProperty.getPkey().equals("color")){
					String color = productProperty.getValue();//得到颜色值
					shopcar_item_prodId_text.setText(color);
				}else if(productProperty.getPkey().equals("size")){
					String  size= productProperty.getValue();//得到大小
					shopcar_item_prodPrice_text.setText(size);
				}
			}
//			shopcar_item_prodId_text.setText("颜色");
//			shopcar_item_prodPrice_text.setText("尺码");
//			shopcar_item_num_text.setText("价格");
			shopcar_item_num_text.setText(productPrice+"");
			int productprom = cartItem.getProductprom();//购买数量
			summary_total_buycount+=productprom;
//			shopcar_item_subtotal_text.setText("数量");
			shopcar_item_subtotal_text.setText(""+productprom);
			String totalPrice = GloableParams.cartMap.get("totalPrice").toString();
//			summary_item_num_text.setText("小计");
			summary_item_num_text.setText(""+product.getPrice()*productprom);
			summary_total_bonus+=Float.parseFloat(totalPrice);
			
			return v;
		}
	}
	
	//按钮点击事件的实现
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()){
		case R.id.head_shopping_cart:
			//返回购物车
			System.out.println("返回购物车");
			 intent=new Intent(SummaryPaymentActivity.this,CartActivity.class);
			 startActivity(intent);
			break;
		
		case R.id.summary_receiver_rel:
			System.out.println("跳转到收货人信息");
			intent=new Intent(SummaryPaymentActivity.this,DiZhiGuanLiActivity.class);
			startActivityForResult(intent, PERSONINFO);
			break;
		case R.id.summary_payType_rel:
			//返回购物车
			System.out.println("支付方式");
			intent=new Intent(this,PayWayActivity.class);
			startActivityForResult(intent, PAYWAYREQUEST);//跳转页面
			break;
		case R.id.summary_sendTime_rel:
			System.out.println("跳转到送货时间");
			intent=new Intent(this,SendTimeActivity.class);
			startActivityForResult(intent, SENDTIMEREQUEST);//跳转页面
			break;
		case R.id.summary_sendeway_rel:
			System.out.println("跳转到送货方式");
			
			break;
		case R.id.summary_favorable_rel:
			System.out.println("使用优惠劵");
			intent=new Intent(this,YouHuiKaActivity.class);
			startActivityForResult(intent, YOUHUIKAREQUEST);//跳转页面
			break;
		case R.id.request_invoice:
			System.out.println("索取发票");
			intent=new Intent(this,FaPiaoFillActivity.class);
			startActivityForResult(intent, FAPIAOREQUEST);//跳转页面
			break;
		case R.id.head_submit_order:
//			//跳转到提交订单
//			System.out.println("跳转到提交订单");
//			intent=new Intent(SummaryPaymentActivity.this,OrderCommitOkActivity.class);
//			startActivity(intent);
//			break;
		case R.id.ordr_submit_bottom_text:
			System.out.println("提交订单");
			//开启线程将数据传入服务器
			//1.向订单表中插入数据
			//①随机生成订单id 拼接时间
			Random ran=new Random();
			ranOrderId=(ran.nextInt(100)+ (int)System.currentTimeMillis());
			if(addressId==0||payType==0||sendTimeType==0){
				Toast.makeText(SummaryPaymentActivity.this, "带星号的信息必须填上，亲~~", 0).show();
				return;
			}
			sendData();
			break;
		}
	}
	/**
	 * 商品id的集合
	 */
	private String productIds="";
	private TextView summary_receiver_info_text;
	private int addressId;
	private MyBaseAdapter adapter;
	private TextView summary_getinvoice_detail;
	private int invoiceContent;//发票内容
	private int invoiceTitle;//发票头
	//发送数据 
	private void sendData() {
		PromptManager.showProgressDialog(SummaryPaymentActivity.this);
		new MyHttpTask() {			
			
			@Override
			protected Object doInBackground(Void... params) {
				CheckOutEngineImpl checkOutEngineImpl=new CheckOutEngineImpl();
				/*	
				 * `order_id` ranOrderId
				 * `user_id` ：GloableParams.userid;
					addressid;// 地址id 
					status:0未处理 1处理
					time：现在时间  
					price：summary_total_bonus
					flag：1.可修改
					`payment_info_type`  payType
					`delivery_info_type` sendTimeType
					`invoice_info_id`  发票id 也是随机生成
					`total_count`  summary_total_buycount
					`total_point` 商品积分 productScore
					`freight`：   summary_freight_money
					`prom_cut`: summary_cuxiao_money 
					`total_price` summary_shouldpay_money
				*/
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("order_id", ranOrderId);
				map.put("addressid", addressId);//TODO//地址id???
				map.put("status", 1);
				map.put("time", "2014");
				map.put("price", summary_total_bonus);
				map.put("flag", 1);
				map.put("delivery_info_type", sendTimeType);
				map.put("payment_info_type", payType);
				
				invoice_info_id = (int)(new Random().nextInt(20)+ System.currentTimeMillis());
				map.put("invoice_info_id", invoice_info_id+"");
				
				map.put("total_count", summary_total_buycount+"");
				map.put("total_point", productScore);
				map.put("freight", summary_freight_money);
				map.put("prom_cut", summary_cuxiao_money);
				map.put("total_price", summary_shouldpay_money);
				map.put("user_id", GloableParams.userid);
				
				map.put("productIds", productIds);//商品id
				if(0<invoiceTitle&&invoiceTitle<=1&&invoiceContent<=4&&invoiceContent>=0){
				map.put("invoiceTitle", invoiceTitle);
				map.put("invoiceContent", invoiceContent);
				}
				//发送到checkout 服务器处理 页面
				@SuppressWarnings("unused") 
				JSONObject json = checkOutEngineImpl.getJson(BaseEngine.TYPE_POST, GloableParams.LZLURLCOMMON+GloableParams.LZLORDERSUMBIT, map);
//				
//				HttpUtil httpUtil=new HttpUtil();
//				 
//				String json = httpUtil.sendPost(GloableParams.LZLURLCOMMON+GloableParams.LZLCONTENT, map, null);
				
				//判断服务器返回的数据
//				try{
//					JSONObject jsonObject=new JSONObject();
//					jsonObject=JSON.parseObject(json.toString());
//					String res = jsonObject.getString("response");//得到解析中的response信息
//					if(res.equals("checkout")){
//						String orderinfo = jsonObject.getString("orderinfo");
//						OrderInfo addressInfo = JSONObject.parseObject(orderinfo,OrderInfo.class);
//						return addressInfo;
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//				}//相当于服务器中map集合
				return null;
			}
			protected void onPostExecute(Object result) {
				PromptManager.closeProgressDialog();
				Intent intent=new Intent(SummaryPaymentActivity.this,OrderCommitOkActivity.class);
				intent.putExtra("ranOrderId",String.valueOf(ranOrderId));//订单编号
				intent.putExtra("summary_shouldpay_money",summary_shouldpay_money );//应付金额
				intent.putExtra("payType", payType);//支付方式
				startActivityForResult(intent, ORDERREQUEST);
			};
		}.executeHttp();
	}
	@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			if(requestCode==PAYWAYREQUEST&&resultCode==Activity.RESULT_OK){//如果返回的是支付方式
				int type = data.getIntExtra("type", 0);//返回支付方式
				//TODO 完成支付方式页面返回的数据 
				System.out.println("返回的支付方式为："+type);
				String text="";
				if(type==1){
					text="到付-现金";
				}else if(type==2){
					text="到付-poss";
				}else if(type==3){
					text="支付宝";
				}
				payType=type;
				summary_payway_detail.setText(text);
			}
			//1 => 周一至周五送货 2=> 双休日及公众假期送货 3=> 时间不限，工作日双休日及公众假期均可送货
			if(requestCode==SENDTIMEREQUEST&&resultCode==Activity.RESULT_OK){//如果返回的是支付方式
				int type = data.getIntExtra("type", 0);//返回支付方式
				//TODO 完成支付方式页面返回的数据 
				System.out.println("返回的送货方式为："+type);
				String text="";
				if(type==1){
					text="只工作日";
				}else if(type==2){
					text="双休日、假日送货 ";
				}else if(type==3){
					text="工作日、双休日及假日均可送货";
				}
				sendTimeType=type;
				summary_sendtime_detail.setText(text);
			}
			
			//使用优惠卡：type1 优惠卡信息一 type 2：。。二  3.。。
			if(requestCode==YOUHUIKAREQUEST&&resultCode==Activity.RESULT_OK){//如果返回的是支付方式
				int type = data.getIntExtra("type",0);//返回优惠卡信息
				System.out.println("使用优惠劵的类型为："+type);
				if(type!=0){
					//不为空
					summary_useyouhuijuan_detail.setText("是");
				}else{
					summary_useyouhuijuan_detail.setText("否");
				}
				youHuiKaType=type;
			}
			//使用优惠卡：type1 优惠卡信息一 type 2：。。二  3.。。
			if(requestCode==PERSONINFO&&resultCode==Activity.RESULT_OK){//如果返回的是支付方式
				addressId = data.getIntExtra("addressId", 0);
				int areaId= data.getIntExtra("areaId", 0);
				String areaDetail= data.getStringExtra("areaDetail");
				String phonenumber = data.getStringExtra("phonenumber");
				//查询电话 
				summary_receiver_info_text.setText(GloableParams.username+"\n"+phonenumber+"\n"+areaId+" "+areaDetail+"\n");
			}
			if(requestCode==FAPIAOREQUEST&&resultCode==Activity.RESULT_OK){//如果返回的是支付方式
				invoiceTitle = data.getIntExtra("invoiceTitle", -1);
				invoiceContent = data.getIntExtra("invoiceContent", -1);
				if(0<invoiceTitle&&invoiceTitle<=1&&invoiceContent<=4&&invoiceContent>=0){
					summary_getinvoice_detail.setText("是");
				}else{
					summary_getinvoice_detail.setText("否");
				}
				//查询电话 
			}
			
			
		}
}
